package main

import (
	"context"
	"fmt"
	"go.etcd.io/etcd/api/v3/mvccpb"
	"go.etcd.io/etcd/client/v3"
	"time"
)

func main() {
	var (
		config    clientv3.Config
		client    *clientv3.Client
		kv        clientv3.KV
		err       error
		getResp   *clientv3.GetResponse
		watchChan <-chan clientv3.WatchResponse
		watchResp clientv3.WatchResponse
		event     *clientv3.Event
	)
	config = clientv3.Config{
		Endpoints:   []string{"47.106.109.134:2379"},
		DialTimeout: 5 * time.Second,
	}
	if client, err = clientv3.New(config); err != nil {
		fmt.Println(err)
		return
	}
	// read and write etcd k,v
	kv = clientv3.NewKV(client)
	go func() {
		for {
			kv.Put(context.TODO(), "cron/jobs/job7", "I am job7")
			kv.Delete(context.TODO(), "cron/jobs/job7")
			time.Sleep(1 * time.Second)
		}
	}()

	// get and watch
	ctx, cancelFunc := context.WithCancel(context.TODO())
	time.AfterFunc(5 * time.Second, func() {
		cancelFunc()
	})

	if getResp, err = kv.Get(context.TODO(), "cron/jobs/job7"); err != nil {
		fmt.Println(err)
		return
	}
	if len(getResp.Kvs) != 0 {
		fmt.Println(string(getResp.Kvs[0].Value))
	}

	// watch the start of the revision
	watchStartRevision := getResp.Header.Revision + 1
	fmt.Println("next watch: ", watchStartRevision)

	// create watcher
	watcher := clientv3.NewWatcher(client)

	// start the watcher
	watchChan = watcher.Watch(ctx, "cron/jobs/job7", clientv3.WithRev(watchStartRevision))
	for watchResp = range watchChan {
		for _, event = range watchResp.Events {
			switch event.Type {
			case mvccpb.PUT:
				fmt.Println("changed to: ", string(event.Kv.Value), "Revision: ", event.Kv.CreateRevision, event.Kv.ModRevision)
			case mvccpb.DELETE:
				fmt.Println("deleted : ", "Revision: ", event.Kv.ModRevision)
			}
		}
	}
}
